package com.ktwlsoft.archivemanage.domain.business.repositoryService;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.businessService.SecurityRoleService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiGuidanceMendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuidanceApplyRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.mend.MendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiGuidanceMendList;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuidanceApply;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendList;
import com.ktwlsoft.archivemanage.domain.dao.repository.NotifyMessageMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import com.ktwlsoft.archivemanage.service.utils.webSocket.WebSocketMyClient;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class NotifyMessageRepositoryService {

    @Getter
    private final NotifyMessageMapper notifyMessageMapper;

    private final WebSocketMyClient client;

    private final MendListRepositoryService mendListRepositoryService;

    /**业务指导整改*/
    private final GuiGuidanceMendListRepositoryService listRepositoryService;

    /**年度报送*/
    private final AnnualReportRepositoryService annualReportRepositoryService;

    /**指导申请*/
    private final GuidanceApplyRepositoryService applyRepositoryService;

    /**用户*/
    private final AccountRepositoryService accountRepositoryService;

    /**角色安全相关*/
    private final SecurityRoleService securityRoleService;

    private Logger logger = LoggerFactory.getLogger(NotifyMessageRepositoryService.class);

    public NotifyMessageRepositoryService(NotifyMessageMapper notifyMessageMapper, WebSocketMyClient client, MendListRepositoryService mendListRepositoryService, GuiGuidanceMendListRepositoryService listRepositoryService, AnnualReportRepositoryService annualReportRepositoryService, GuidanceApplyRepositoryService applyRepositoryService, AccountRepositoryService accountRepositoryService, SecurityRoleService securityRoleService) {
        this.notifyMessageMapper = notifyMessageMapper;
        this.client = client;
        this.mendListRepositoryService = mendListRepositoryService;
        this.listRepositoryService = listRepositoryService;
        this.annualReportRepositoryService = annualReportRepositoryService;
        this.applyRepositoryService = applyRepositoryService;
        this.accountRepositoryService = accountRepositoryService;
        this.securityRoleService = securityRoleService;
    }

    @Transactional(rollbackFor = Exception.class)
    public int insertNotifyMessage(
            @NotNull Long businessId,
            @NotNull NotifyMessage.RemindType remindType,
            @NotNull String otherContent,
            @NotNull NotifyMessage.BelongBusiness belongBusiness,
            String relatedPerson,
            Long relatedPersonId,
            @NotNull String mainBody,
            @NotNull Long mainBodyId,
            @NotNull Integer export) {
        if(export.equals(0)) {
            JSONObject object = new JSONObject();
            object.put("businessId", businessId != null ? String.valueOf(businessId) : "");
            object.put("remindType", remindType != null ? remindType : "");
            object.put("otherContent", otherContent != null ? otherContent : "");
            object.put("belongBusiness", belongBusiness != null ? handleBelongBusiness(belongBusiness,businessId) : "");
            Account account = new Account();
            account.setRoleName("管理员");
            List<Account> accounts = accountRepositoryService.checkUnique(account);
            //注册审核
            if(NotifyMessage.BelongBusiness.REGISTER_SAVE.equals(belongBusiness)){
                if (accounts != null && accounts.size() > 0) {
                    for (Account account1 : accounts) {
                        List<ActionSource> userActions = securityRoleService.findActionsByUserName(account1.getUserName());
                        List<ActionSource> list = Lists.newArrayList();
                        if (userActions != null && userActions.size() > 0) {
                            list = userActions.stream().filter(value -> "注册审核".equals(value.getRemark())).collect(Collectors.toList());
                        }
                        if (list.size() > 0) {
                            try {
                                client.sendMessage(String.valueOf(account1.getId()), object);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }else {
                if (accounts != null && accounts.size() > 0) {
                    for (Account account1 : accounts) {
                        try {
                            client.sendMessage(String.valueOf(account1.getId()), object);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }else{
            if (relatedPersonId != null && relatedPersonId != 0) {
                JSONObject object = new JSONObject();
                object.put("businessId", businessId != null ? String.valueOf(businessId) : "");
                object.put("remindType", remindType != null ? remindType : "");
                object.put("otherContent", otherContent != null ? otherContent : "");
                object.put("belongBusiness", belongBusiness != null ? handleBelongBusiness(belongBusiness,businessId) : "");
                try {
                    client.sendMessage(String.valueOf(relatedPersonId), object);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return notifyMessageMapper.insert(new NotifyMessage(
                SnowFlake.getNextId(),
                new Date(),
                businessId,
                belongBusiness,
                NotifyMessage.BelongSystem.ARCHIVE_BUSINESS_INSTRUCTION_SYSTEM,
                remindType,
                otherContent,
                0,
                relatedPerson,
                relatedPersonId,
                mainBody,
                mainBodyId,
                export,
                0)
        );
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<?> findByPage(Integer pn, Integer pageSize, Long recorderId, Long export, Account account){
        PageInfo<NotifyMessage> pageInfo = findAllByPage(pn, pageSize, recorderId, export,account);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            pageInfo.setList(pageInfo.getList().stream().map(value ->{
                if(value.getBelongBusiness().equals(NotifyMessage.BelongBusiness.MEND)){
                    MendList mendList =  mendListRepositoryService.findById(value.getBusinessId());
                    if(mendList != null && mendList.getMendState().equals(MendList.MendState.WAIT_VERIFY)){
                        value.setBelongBusiness(NotifyMessage.BelongBusiness.MEND_NO);
                    }
                }else if(value.getBelongBusiness().equals(NotifyMessage.BelongBusiness.GUI_MEND)){
                    GuiGuidanceMendList mendList = listRepositoryService.getById(value.getBusinessId());
                    if(mendList != null && mendList.getMendState().equals(2)){
                        value.setBelongBusiness(NotifyMessage.BelongBusiness.GUI_MEND_NO);
                    }
                }else if(value.getBelongBusiness().equals(NotifyMessage.BelongBusiness.ANNUAL_REPORT)){
                    ReportDetail reportDetail = annualReportRepositoryService.findAnnualReportInfo(value.getBusinessId());
                    if(reportDetail != null && "WAIT".equals(reportDetail.getState())){
                        value.setBelongBusiness(NotifyMessage.BelongBusiness.ANNUAL_REPORT_NO);
                    }
                }else if(value.getBelongBusiness().equals(NotifyMessage.BelongBusiness.GUIDANCE_APPLY)){
                    GuidanceApply apply = applyRepositoryService.getById(value.getBusinessId());
                    if(apply != null && apply.getState().equals(2)){
                        value.setBelongBusiness(NotifyMessage.BelongBusiness.GUIDANCE_APPLY_NO);
                    }
                }
                return value;
            }).collect(Collectors.toList()));
        }
        return Result.ok(pageInfo);
    }

    public PageInfo<NotifyMessage> findAllByPage(Integer pn, Integer pageSize, Long recorderId, Long export, Account account) {
        PageHelper.startPage(pn, pageSize);
        return new PageInfo<>(notifyMessageMapper.selectByRelatePersonId(recorderId, export,account.getId()));
    }

    public void setMsgRead(Long id) {
        notifyMessageMapper.setConsumed(id);
    }

    /**
      * 处理业务状态 on 2020/7/23 14:30
      *
      * @param belongBusiness belongBusiness
      * @param businessId businessId
      * @return NotifyMessage.BelongBusiness
      */
    public NotifyMessage.BelongBusiness handleBelongBusiness(NotifyMessage.BelongBusiness belongBusiness,Long businessId){
        if(belongBusiness.equals(NotifyMessage.BelongBusiness.MEND)){
            MendList mendList =  mendListRepositoryService.findById(businessId);
            if(mendList != null && mendList.getMendState().equals(MendList.MendState.WAIT_VERIFY)){
                return NotifyMessage.BelongBusiness.MEND_NO;
            }
        }else if(belongBusiness.equals(NotifyMessage.BelongBusiness.GUI_MEND)){
            GuiGuidanceMendList mendList = listRepositoryService.getById(businessId);
            if(mendList != null && mendList.getMendState().equals(2)){
                return NotifyMessage.BelongBusiness.GUI_MEND_NO;
            }
        }else if(belongBusiness.equals(NotifyMessage.BelongBusiness.ANNUAL_REPORT)){
            ReportDetail reportDetail = annualReportRepositoryService.findAnnualReportInfo(businessId);
            if(reportDetail != null && "WAIT".equals(reportDetail.getState())){
                return NotifyMessage.BelongBusiness.ANNUAL_REPORT_NO;
            }
        }else if(belongBusiness.equals(NotifyMessage.BelongBusiness.GUIDANCE_APPLY)){
            GuidanceApply apply = applyRepositoryService.getById(businessId);
            if(apply != null && apply.getState().equals(2)){
                return NotifyMessage.BelongBusiness.GUIDANCE_APPLY_NO;
            }
        }
        return belongBusiness;
    }
}
